package com.gitee.feizns.explore.data_structure.linked_list.singly.reverseList;

import com.gitee.feizns.explore.data_structure.linked_list.singly.ListNode;

/**
 * @author feizns
 * @since 2020/3/5
 */
public class ReverseList {

    public static void main(String[] args) {
        println(reverseList(create()));
    }

    private static void println(ListNode x) {
        ListNode tmp = x;
        while ( tmp != null ) {
            System.out.print(tmp.val);
            tmp = tmp.next;
        }
    }

    private static ListNode create() {
        ListNode r = new ListNode(1);
        r.next = new ListNode(2);
        r.next.next = new ListNode(3);
        return r;
    }

    public static ListNode reverseList(ListNode head) {
        return head != null ? recursive(head) : null;
    }

    private static ListNode recursive(ListNode node) {
        if ( node.next != null ) {
            ListNode root = recursive(node.next);
            node.next.next = node;
            node.next = null;
            return root;
        }
        return node;
    }

}
